#!/bin/bash
#########################################################################################
# (C) Copyright NetEnrich Inc., 2012, All Rights Reserved.                              #
# File Name                     : build.sh                                              #
# Purpose                       : To update the itop set up                             #
#                               :                                                       #
#                               :                                                       #
#                               :                                                       #
# Version                       : 1.0                                                   #
# Revision                      :                                                       #
# Original Author               : Ambuj Jain                                            #
# Date                          : Oct 22, 2012                                          #
# Modification details          :                                                       #
# Reviewed By                   :                                                       #
# Tested by                     :                                                       #
#########################################################################################

export LANG=C

# Check we're running as root
if [ "$(id -u)" != "0" ]; then
  echo "The update script must be run as root"
  exit 1
fi

BASEDIR=$(dirname $0)
cd $BASEDIR

if [ "$#" -ne 1 ] || ! [ "$1" == "db" -o "$1" == "itop" -o "$1" == "cn" ] 
then
  echo 
  echo "Please provide the server type to be updated. [db | itop | cn]"
  echo "Usage: $0 <cn|db|itop>"
  echo
  exit 1
fi

LOGFILE="$BASEDIR/install.log";

update_activemq(){
  rm -fr /opt/activemq
  tar --no-same-owner -xzf db/apache-activemq-5.9.0-bin.tar.gz -C /opt
  mv /opt/apache-activemq-5.9.0 /opt/activemq
  cp -f db/init.d/activemq /etc/init.d/activemq
  chmod +x /etc/init.d/activemq
  service activemq restart
}
  
remove_activemq(){
  echo "Stopping service activemq" | tee -a $LOGFILE
  service activemq stop >/dev/null 2>&1
  update-rc.d -f activemq remove | tee -a $LOGFILE
  rm -fr /opt/activemq /etc/init.d/activemq
}

add_kafka(){
  echo "Added itop user in db node" | tee -a $LOGFILE
  useradd -u 1002 -U itop
  sed -i 's/activemq-server/kafka/g' /etc/hosts
  sed -i "2 a\127.0.0.1\tapp52 cassandra-db" /etc/hosts

  echo "Creating Directories for kafka and zk" | tee -a $LOGFILE
  mkdir /var/lib/kafka /var/lib/zk
  chmod -R 777 /var/lib/kafka /var/lib/zk
  chown -R itop:itop /var/lib/kafka /var/lib/zk

  echo "Installing kafka and zk" >>$LOGFILE | tee -a $LOGFILE
  tar -xzf db/kafka_2.10-0.8.1.1.tar.gz -C /opt/
  mv /opt/kafka_2.10-0.8.1.1 /opt/kafka
  chown -R itop:itop /opt/kafka
  mkdir /var/log/kafka /var/log/zk -p
  chown -R itop:itop /var/log/kafka /var/log/zk
  cp db/init.d/kafka db/init.d/zk /etc/init.d/
  chmod +x /etc/init.d/kafka /etc/init.d/zk
  update-rc.d zk defaults | tee -a $LOGFILE
  update-rc.d kafka defaults | tee -a $LOGFILE
  service zk restart
  sleep 4
  service kafka restart
}

add_cassandra(){
	echo "Configuring Cassandra..." | tee -a $LOGFILE
	tar -xvzpf db/cassandra-configs.tar.gz -C /etc/cassandra/ >>$LOGFILE
	service cassandra stop >>$LOGFILE
	rm -fr /var/lib/cassandra/data/system/*
	echo "Extracted configurations..." | tee -a $LOGFILE
	deploy_cassandra_schema
}

add_mysql_conf(){
	cp db/my.cnf /etc/mysql/
	chmod 644 /etc/mysql/my.cnf
	service mysql restart
	echo "Added my.cnf in DB node..." | tee -a $LOGFILE
}

deploy_cassandra_schema(){
	echo "Installing cassandra schema..." | tee -a $LOGFILE
	CAT="/bin/cat"
	SQL_FILES_DIR="/opt/sql"
	service cassandra restart
	sleep 30
	service cassandra status
	for LINE in `cat $SQL_FILES_DIR/cassandra-schema-install.fifo`
	do
	    LINE=$(echo "$LINE" | sed -e 's/[[:space:]]*//')
	    SQL_FILE=$SQL_FILES_DIR$LINE
	    #echo $SQL_FILE
	    
	    fromdos $SQL_FILE
	    /usr/bin/cqlsh -ucassandra -pcassandra -f $SQL_FILE
	    if [ $? -ne 0 ]; then
	    	echo "Failed to install the Cassandra schema from $LINE"
	    fi
	done

}

updateJava(){
  echo "Updating JAVA Version 1.7.0_65..." | tee -a $LOGFILE
  apt-get -y install oracle-java7-installer | tee -a $LOGFILE
  echo "Removing sun-java6-bin and sun-java6-jre..." | tee -a $LOGFILE
  apt-get -y purge sun-java6-bin sun-java6-jre | tee -a $LOGFILE
}

updateUFW () {
    if [ -f $1/ufw/before.rules ];
    then
	cp -f $1/ufw/before.rules /etc/ufw/before.rules
	R1=$?
	service ufw restart  >> $LOGFILE 2>&1
	R2=$?
	if [ $R1 -eq 0 -a $R2 -eq 0 ]; then
		echo "SUCCESS: Update firewall" >> $LOGFILE;
	else
		echo "FAILURE: Update firewall" >> $LOGFILE;
		return 1;
	fi
	return 0
    fi
}

add_nfs_mon_script(){
	#line="*/10 * * * * /opt/scripts/check_nfs_mount.sh >/dev/null 2>&1"
	#echo "SNMP change to monitor nfs mount" | tee -a $LOGFILE
	cp -f scripts/check_nfs_mount.sh /opt/scripts/check_nfs_mount.sh
	chmod +x /opt/scripts/check_nfs_mount.sh
	
	# Remove existing cron entry.
	/usr/bin/crontab -u root -l | grep check_nfs_mount
	if [ $? -eq 0  ]; then
		/usr/bin/crontab -u root -l > /tmp/cron-list.txt
		sed -i '/\/opt\/scripts\/check_nfs_mount.sh/d' /tmp/cron-list.txt
		/usr/bin/crontab -u root /tmp/cron-list.txt
		echo "NFS cron entry removed sucessfully"  >> $LOGFILE
		return $?
	fi
	
	#if [ $? -ne 0  ]; then
	#       (/usr/bin/crontab -u root -l; echo "$line" ) | /usr/bin/crontab -u root -
	#       echo "NFS monitoring script is added to cron"  >> $LOGFILE
	#       return $?
	#else
	#       echo "NFS monitoring script is already added to cron"  >> $LOGFILE
	#fi
	
	#/bin/mount -t nfs,nfs4|grep /opt/datastore >/dev/null 2>&1
	/bin/mount -t nfs,nfs4 | grep "^.* on /opt/datastore type nfs.*$" > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		touch /opt/datastore/.nfs_stale_test
		chmod 666 /opt/datastore/.nfs_stale_test
	fi
	
	return 0
}

add_itop_cron_entries(){
	#line="*/10 * * * * /opt/scripts/check_nfs_mount.sh >/dev/null 2>&1"
	#line2="0 1 * * * /bin/su -c '/usr/bin/find /opt/datastore/ncare/data/recordings/decrypt -type d -name "*-*" -mtime +2 -exec rm -fr {} \;' itop >/dev/null 2>&1"
	
	line1="0 0 * * * /bin/rm -fr /opt/itop/temp/DataEngine_* >/dev/null 2>&1"
	line2="0 2 * * * /bin/su -c '/usr/bin/find /opt/datastore/ncare/data/recordings/decrypt -type d -name \"*-*\" -mtime +2 | xargs rm -fr' itop >/dev/null 2>&1"
	line3="1 2 * * * /bin/su -c '/usr/bin/find /opt/itop/logs/ -type f -name \"localhost_access_log*\" -mtime +10 | xargs rm -fr' itop >/dev/null 2>&1"
	line4="2 2 * * * /bin/su -c '/usr/bin/find /opt/itop/webapps/ROOT/logs/ -type f -name \"*log\" -mtime +10 | xargs rm -fr' itop >/dev/null 2>&1"
	/usr/bin/crontab -u root -l | grep DataEngine_
	if [ $? -ne 0  ]; then
		(/usr/bin/crontab -u root -l; echo "$line1" ) | /usr/bin/crontab -u root -
		echo "Remove BIRT files is added to cron"  >> $LOGFILE
	else
		echo "Remove BIRT files is already added to cron"  >> $LOGFILE
	fi
	/usr/bin/crontab -u root -l | grep recordings/decrypt
	if [ $? -ne 0  ]; then
		(/usr/bin/crontab -u root -l; echo "$line2" ) | /usr/bin/crontab -u root -
		echo "Remove decrypt recordings is added to cron"  >> $LOGFILE
	else
		echo "Remove decrypt recordings is already added to cron"  >> $LOGFILE
	fi
	/usr/bin/crontab -u root -l | grep localhost_access_log
	if [ $? -ne 0  ]; then
		(/usr/bin/crontab -u root -l; echo "$line3" ) | /usr/bin/crontab -u root -
		echo "Remove localhost_access_log files is added to cron"  >> $LOGFILE
	else
		echo "Remove localhost_access_log files is already added to cron"  >> $LOGFILE
	fi
	/usr/bin/crontab -u root -l | grep '/opt/itop/webapps/ROOT/logs'
	if [ $? -ne 0  ]; then
		(/usr/bin/crontab -u root -l; echo "$line4" ) | /usr/bin/crontab -u root -
		echo "Remove /opt/itop/webapps/ROOT/logs/ files is added to cron"  >> $LOGFILE
	else
		echo "Remove /opt/itop/webapps/ROOT/logs/ files is already added to cron"  >> $LOGFILE
	fi
	return 0
}

tcp_tuning(){

  	grep net.ipv4.tcp_slow_start_after_idle /etc/sysctl.conf > /dev/null 2>&1
	if [ $? -ne 0  ]; then
	  cat <<EOF >> /etc/sysctl.conf
# not to start with default window size for existing TCP connections that have been idle for too long 
net.ipv4.tcp_slow_start_after_idle=0
# Set maximum network input buffer queue length
net.core.netdev_max_backlog = 10000
# Set maximum TCP window sizes
net.core.rmem_max = 12582912
net.core.wmem_max = 12582912
# Set minimum, default, and maximum TCP buffer limits
net.ipv4.tcp_rmem = 8192 87380 12582912
net.ipv4.tcp_wmem = 8192 87380 12582912
net.core.rmem_default=229376
net.core.wmem_default=229376
# don't touch tcp_mem for two reasons: Firstly, unlike tcp_rmem and tcp_wmem it's in pages, not bytes, so it's likely to confuse the hell out of you. Secondly, it's already auto-tuned very well by Linux based on the amount of RAM.
#net.ipv4.tcp_mem= 8388608 8388608 8388608
# congestion control (default cubic)
# /sbin/modprobe tcp_htcp
# sysctl net.ipv4.tcp_available_congestion_control
net.ipv4.tcp_congestion_control=htcp
# Disable caching of TCP congestion state (2.6 only). TCP will not cache metrics on closing connections.
net.ipv4.tcp_no_metrics_save = 1
# increase port range
net.ipv4.ip_local_port_range = 18000    65535
#enable window scaling
net.ipv4.tcp_window_scaling=1
# tcp selective acknowledgements. should be enabled (for wide area network communication), but it can increase CPU utilization.
net.ipv4.tcp_sack = 1
# disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
# enables calculation of RTT in a more accurate way (see RFC 1323) than the retransmission timeout; should be enabled for performance.
net.ipv4.tcp_timestamps = 1
# discourages the kernel from swapping idle processes to disk (default = 60)
vm.swappiness=10
# Disable source routing and redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.default.accept_source_route = 0
# Log packets with impossible addresses for security
net.ipv4.conf.all.log_martians = 1 
# Make room for more TIME_WAIT sockets due to more clients,
# and allow them to be reused if we run out of sockets
# Also increase the max packet backlog
net.ipv4.tcp_max_syn_backlog = 10000
#net.ipv4.tcp_max_tw_buckets = 360000
# allow to reuse TIME_WAIT sockets for new connections
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 20
# enable fast recycling of TIME_WAIT sockets.. *** Don't use when working with NAT ***
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syn_retries = 2
#maximum number of times a SYN/ACK segment for a passive TCP connection will be retransmitted
net.ipv4.tcp_synack_retries = 2
#maximum number of TCP keep-alive probes to send before giving up
net.ipv4.tcp_keepalive_probes = 3
#send out syncookies when the syn backlog queue of a socket overflows
net.ipv4.tcp_syncookies = 1
#number of attempts made to probe the other end of a connection which has been closed by our end
net.ipv4.tcp_orphan_retries = 1
# If your servers talk UDP, also up these limits
net.ipv4.udp_rmem_min = 8192
net.ipv4.udp_wmem_min = 8192
#controls TCP Packetization-Layer Path MTU discovery
net.ipv4.tcp_mtu_probing = 1
#net.ipv4.tcp_rfc1337 = 1
# if enabled, TCP performs receive buffer auto-tuning
net.ipv4.tcp_moderate_rcvbuf = 1
# enable TCP Forward Acknowledgement support
net.ipv4.tcp_fack = 1

EOF

    /sbin/sysctl -p /etc/sysctl.conf
  
  else
    echo "TCP tuning has been already done..ignoring.."  >> $LOGFILE
  fi

}

update_reg() {
  if [ -f /opt/admin/bin/reg/reg.pl ];
  then
    echo "Patching the reg.pl file..." | tee -a $LOGFILE
    cp ncare/reg.pl /opt/admin/bin/reg/reg.pl
    chown root.root /opt/admin/bin/reg/reg.pl
    chmod 755 /opt/admin/bin/reg/reg.pl
    echo "Patching the reg.pl file completed" | tee -a $LOGFILE
    
    echo "Re-registration of the Connection server..." | tee -a $LOGFILE
    /usr/bin/perl /opt/admin/bin/reg/reg.pl
    echo "Re-registration of the CSN is completed" | tee -a $LOGFILE
  fi
}

sanitize_snmpd_conf() {
  echo "SNMP configuration change to remove duplicates" | tee -a $LOGFILE
  awk '!seen[$0]++' /etc/snmp/snmpd.conf > snmpd-new.conf
  cp snmpd-new.conf /etc/snmp/snmpd.conf
  echo "Restarting snmpd..." | tee -a $LOGFILE
  service snmpd restart
}

update_network_config(){
  echo "Serial UI script.." | tee -a $LOGFILE
  cp scripts/network-config /opt/scripts/
  chmod +x /opt/scripts/network-config
  echo "Copied network config script" | tee -a $LOGFILE
  cp scripts/prepare_logs.sh /opt/scripts/
  chmod +x /opt/scripts/prepare_logs.sh
  echo "Copied prepare logs script" | tee -a $LOGFILE
}

updateLogrotate() {
    if [ -d $1/logrotate.d ];
    then
	  cp -f $1/logrotate.d/* /etc/logrotate.d/
	  R1=$?
	  /etc/cron.daily/logrotate  >> $LOGFILE 2>&1
	  R2=$?
	  if [ $R1 -eq 0 -a $R2 -eq 0 ]; then
		echo "SUCCESS: Update logrotate cofigs" >> $LOGFILE;
	  else
		echo "FAILURE: Update logrotate cofigs" >> $LOGFILE;
		return 1;
	  fi
	  return 0
    fi
}

snmpd_change() {
  echo "SNMP configuration change to replace acticemq to kafka" | tee -a $LOGFILE
  sed -i "/^exec activemq_service/c\exec kafka_service /opt/scripts/service_check.py kafka" /opt/scripts/templates/snmpd.conf /etc/snmp/snmpd.conf
  # Expecting mongodb_service service will be at index 8, nfs_status may or may not exists.
  grep nfs_status /etc/snmp/snmpd.conf
  if [ $? -ne 0  ]; then
    echo "exec nfs_status /opt/scripts/check_nfs_mount.sh" >> /etc/snmp/snmpd.conf
    echo "Restarting snmpd..." | tee -a $LOGFILE
    service snmpd restart
  else
    echo "NFS mount is already and hence doing nothing.." | tee -a $LOGFILE
  fi
  
  #echo "exec kafka_service /opt/scripts/service_check.py kafka" >> /etc/snmp/snmpd.conf
  echo "exec zk_service /opt/scripts/service_check.py zk" >> /etc/snmp/snmpd.conf
  echo "exec cassandra_service /opt/scripts/service_check.py cassandra" >> /etc/snmp/snmpd.conf
  echo "exec threads_connected /opt/scripts/check_mysql.py Threads_connected" >> /etc/snmp/snmpd.conf
  echo "exec threads_running /opt/scripts/check_mysql.py Threads_running" >> /etc/snmp/snmpd.conf
  echo "exec conn_pool /opt/scripts/check_mysql.py conn_pool" >> /etc/snmp/snmpd.conf
  #sed -i "/^exec activemq_service/c\exec kafka_service /opt/scripts/service_check.py kafka\\nexec zk_service /opt/scripts/service_check.py zk" /etc/snmp/snmpd.conf
  #sed -i "/^exec mongodb_service/c\exec cassandra_service /opt/scripts/service_check.py cassandra" /etc/snmp/snmpd.conf
  
  cp -f scripts/templates/snmpd.conf /opt/scripts/templates/snmpd.conf
  cp -f scripts/service_check.py scripts/check_mysql.py /opt/scripts/
  chmod +x /opt/scripts/service_check.py /opt/scripts/check_mysql.py 
  sanitize_snmpd_conf
}

update_tomcat(){
  rm -fr /opt/itop
  tar -xzf itop/apache-tomcat-7.0.52.tar.gz -C /opt
  mv /opt/apache-tomcat-7.0.52 /opt/itop
  rm -rf /opt/itop/webapps/* /opt/itop/work/* /opt/itop/conf/logging.properties
  mkdir -p /var/log/itop
  chmod -R 777 /var/log/itop
}

add_monit_service(){
  echo "Configure monit service..." | tee -a $LOGFILE
  cp -f $1/monit/conf.d/*.monitrc /etc/monit/conf.d/
  cp -f $1/monit/monitrc /etc/monit/
  chmod 644 /etc/monit/conf.d/*
  service monit stop
  service monit start | tee -a $LOGFILE
  sleep 4
  monit summary | tee -a $LOGFILE
}

updateRepo() {
  echo "Updating OS packages..." | tee -a $LOGFILE
  mkdir /opt/rep
  tar -xvzf commons/debian_packages/dists.tar.gz -C /opt/rep/  >> $LOGFILE 2>&1
  tar -xvzf commons/debian_packages/pool.tar.gz -C /opt/rep/  >> $LOGFILE 2>&1
  echo "deb file:///opt/rep/ precise main" > /etc/apt/sources.list

  apt-get update >> $LOGFILE 2>&1

  pkgs_to_remove=`dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d'`
  if [ "${pkgs_to_remove}" != "" ]
  then
    echo "Removing old kernel packages ...${pkgs_to_remove}" | tee -a $LOGFILE
    dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge | tee -a $LOGFILE
  fi

  echo "Updating kernel..." | tee -a $LOGFILE
  apt-get -y dist-upgrade >> $LOGFILE 2>&1
  updateJava
  if [ "$1" == "db" ]
  then
	#mv /etc/mysql/my.cnf /tmp/
  	apt-get -y install python-support dsc20 monit python-mysqldb| tee -a $LOGFILE
  	#mv /tmp/my.cnf /etc/mysql/
  	sed -i '/Required-Start:/s/$/ $network/' /etc/init.d/monit
    sed -i '/start-stop-daemon --start/i \
    ulimit -n 65535' /etc/init.d/monit
  fi
  
  echo "Removing unwanted packages that are not required anymore..." | tee -a $LOGFILE
  apt-get -y autoremove >> $LOGFILE 2>&1
  rm -fr /opt/rep/
}

update_ncare() {
  while true; do
    echo -n "Have you upgraded Database (y/n)>"
    read choice
    echo
    case $choice in
      [yY] | [yY][Ee][Ss])
        break
        ;;
      [nN] | [n|N][O|o] )
        echo "Not done, you can't proceed the installation";
        return 0
        ;;
      *)
        echo "That is not a valid choice, try again"
        ;;
    esac
  done
  
  echo "Starting upgrade process..." | tee -a $LOGFILE

  updateRepo
  #updateUFW "ncare"
  updateLogrotate "ncare"
  add_monit_service "ncare"

  ETH2_IP=`/sbin/ifconfig eth2 2>&1 | /bin/grep Bcast | /usr/bin/awk '{print $2}' | /usr/bin/awk -F: '{print $2}'`
  ETH3_IP=`/sbin/ifconfig eth3 2>&1 | /bin/grep Bcast | /usr/bin/awk '{print $2}' | /usr/bin/awk -F: '{print $2}'`
  if [ -f /etc/monit/conf.d/ncare.monitrc ];
  then
    if [ "$ETH2_IP" = "" -o "$ETH3_IP" = "" ]; then
      echo "Please configure eth2 and eth3 interfaces before update"
      return 0
    fi
  fi

  if [ -f /etc/monit/conf.d/searchengine.monitrc ];
  then
    echo "Stopping searchengine service..." | tee -a $LOGFILE
    monit stop searchengine  >> $LOGFILE 2>&1
    service searchengined stop >> $LOGFILE 2>&1
  fi
  
  if [ -f /etc/monit/conf.d/ncare.monitrc ];
  then
    echo "Stopping ncare service..." | tee -a $LOGFILE
    monit stop ncare  >> $LOGFILE 2>&1
    service ncare stop >> $LOGFILE 2>&1
  fi
  
  if [ -f /etc/monit/conf.d/rdp2swf.monitrc ];
  then
    echo "Stopping rdp2swf service..." | tee -a $LOGFILE
    monit stop rdp2swf >> $LOGFILE 2>&1
    service rdp2swfd stop >> $LOGFILE 2>&1
  fi

  sleep 8
  
  keyFile="vistara.ks.p12"
  keyPass="N3t@dmin"
  if [ ! -f /opt/ncare/conf/SSLCert.properties ]; then
  	keyFile=`/bin/grep -E -o 'keystoreFile=\"(.*)\"' /opt/ncare/conf/ncare.xml | sed 1q | sed 's/.*keystoreFile="\([^"]*\).*/\1/' | awk -F/  '{print $NF}'`
  	keyPass=`/bin/grep -E -o 'keystorePass=\"(.*)\"' /opt/ncare/conf/ncare.xml | sed 1q | sed 's/.*keystorePass="\([^"]*\).*/\1/' | awk -F/  '{print $NF}'`
    echo "SSLCert.properties does not exist, so reading values from /opt/ncare/conf/ncare.xml ..." | tee -a $LOGFILE
    echo "keystoreFile=\"${keyFile}\"" > /opt/ncare/conf/SSLCert.properties
    echo "keystorePass=\"${keyPass}\"" >> /opt/ncare/conf/SSLCert.properties
    chmod 777 /opt/ncare/conf/SSLCert.properties
  fi
  #echo "Reading SSL properties from file SSLCert.properties..." | tee -a $LOGFILE
  keyFile=`/bin/grep -E -o 'keystoreFile=\"(.*)\"' /opt/ncare/conf/SSLCert.properties | sed 1q | sed 's/.*keystoreFile="\([^"]*\).*/\1/'`
  keyPass=`/bin/grep -E -o 'keystorePass=\"(.*)\"' /opt/ncare/conf/SSLCert.properties | sed 1q | sed 's/.*keystorePass="\([^"]*\).*/\1/'`
  
  cp -f /opt/ncare/conf/ncare.xml .
  cp -fpr /opt/ncare/conf/SSLCert.properties .
  cp -fpr /opt/ncare/conf/$keyFile .
  
  rm -rf /var/log/ncare/*  >> $LOGFILE 2>&1
  rm -fr /opt/ncare/*  >> $LOGFILE 2>&1
  
  echo "Updating the ncare application..." | tee -a $LOGFILE
  
  tar -xvzf ncare/ncare.tar.gz -C /  >> $LOGFILE 2>&1

  if [ -f /etc/monit/conf.d/ncare.monitrc ];
  then
    sed -e "s/@HTTP_IP@/$ETH2_IP/g" -e "s/@TLS_IP@/$ETH3_IP/g" -e "s/@SSL_FILE@/$keyFile/g" -e "s/@SSL_PASS@/$keyPass/g" /opt/ncare/conf/ncare.xml.tpl > /opt/ncare/conf/ncare.xml | tee -a $LOGFILE
  fi
  cp -fpr SSLCert.properties /opt/ncare/conf/SSLCert.properties
  cp -fpr $keyFile /opt/ncare/conf/$keyFile

  fromdos /etc/init.d/ncare >> $LOGFILE 2>&1
  fromdos /etc/init.d/searchengined >> $LOGFILE 2>&1
  fromdos /etc/init.d/rdp2swfd >> $LOGFILE 2>&1
  chown itop.itop /opt/ncare -R >> $LOGFILE 2>&1
  chmod 755 /etc/init.d/ncare /etc/init.d/searchengined /etc/init.d/rdp2swfd /opt/ncare/bin/ -R >> $LOGFILE 2>&1
  mkdir -p /var/log/ncare  >> $LOGFILE 2>&1
  chown itop.itop /var/log/ncare -R >> $LOGFILE 2>&1
  chmod 744 /var/log/ncare -R >> $LOGFILE 2>&1

  sed -i 's/activemq-server/kafka/g' /etc/hosts
  sed -i 's/msp-db/msp-db cassandra-db/g' /etc/hosts
  echo "Doing tcp tunnig and disabling ipv6..." | tee -a $LOGFILE
  tcp_tuning
  
  echo "Adding NFS monitoring script..." | tee -a $LOGFILE
  add_nfs_mon_script
  
  echo "Registering the ncare node..." | tee -a $LOGFILE
  /usr/bin/perl /opt/admin/bin/reg/reg.pl

  echo "Starting the services..." | tee -a $LOGFILE

  if [ -f /etc/monit/conf.d/searchengine.monitrc ];
  then
    echo "Starting service searchengine..." | tee -a $LOGFILE
    monit start searchengine
  fi
  
  if [ -f /etc/monit/conf.d/ncare.monitrc ];
  then
    echo "Starting service ncare..." | tee -a $LOGFILE
    monit start ncare
  fi
  
  if [ -f /etc/monit/conf.d/rdp2swf.monitrc ];
  then
    echo "Starting service rdp2swf..." | tee -a $LOGFILE
    monit start rdp2swf
  fi

  update_reg

  sleep 5

  snmpd_change
  update_network_config
  
  echo "The node has been successfully updated..." | tee -a $LOGFILE
  return 0
}

update_db() {
  while true; do
    echo -n "Have you stopped services in all CN nodes (CS, RDP2SWF and SE) and itop (y/n)>"
    read choice
    echo
    case $choice in
      [yY] | [yY][Ee][Ss])
        break
        ;;
      [nN] | [n|N][O|o] )
        echo "Not done, you can't proceed the installation";
        return 0
        ;;
      *)
        echo "That is not a valid choice, try again"
        ;;
    esac
  done
  
  echo "Starting upgrade process..." | tee -a $LOGFILE

  updateUFW "db"
  updateLogrotate "db"

  d=`date +%s`
  dump_dir=/var/lib/mysqldump/$d
  mkdir -p $dump_dir
    
  echo "Starting DB backup in directory $dump_dir ..." | tee -a $LOGFILE
  mysqldump -umsp -pmsp msp > $dump_dir/msp.sql --skip-lock-tables 2>&1
  mysqldump -umsp_report -pmsp_report msp_report > $dump_dir/msp_report.sql --skip-lock-tables 2>&1
  mysqldump -umsp_mon -pmsp_mon msp_mon > $dump_dir/msp_mon.sql --skip-lock-tables 2>&1 

  updateRepo "db"
  add_monit_service "db"
  
  echo "Starting Database upgrade..." | tee -a $LOGFILE
  tar -xvzf db/itop-db.tar.gz -C / >> $LOGFILE 2>&1
  sh /opt/sql/upgrade.sh >> $LOGFILE 2>&1
  mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -pxAVa6Aze mysql
  rm /opt/sql/upgrade.sh /install.sh >> $LOGFILE 2>&1
  
  cp -f db/db_backup /opt/scripts/
  cp -f db/db_restore /opt/scripts/
  chmod 755 /opt/scripts/db_restore

  #update_activemq
  snmpd_change
  update_network_config
  
  echo "Doing tcp tunnig and disabling ipv6..." | tee -a $LOGFILE
  tcp_tuning
  remove_activemq
  echo "Completed purging activemq" | tee -a $LOGFILE
  add_kafka
  echo "Completed adding kafka and zookeeper" | tee -a $LOGFILE
  add_cassandra
  echo "Completed adding Cassandra" | tee -a $LOGFILE
  add_mysql_conf
  
  echo "DB backup and restore script.." | tee -a $LOGFILE
  cp scripts/db_backup scripts/db_restore /opt/scripts/
  chmod +x /opt/scripts/db_backup /opt/scripts/db_restore
  echo "Copied database backup and restore scrips" | tee -a $LOGFILE
  
  echo "Adding NFS monitoring script..." | tee -a $LOGFILE
  add_nfs_mon_script

  echo "The node has been successfully updated..." | tee -a $LOGFILE
  return 0
}

update_itop() {
  while true; do
    echo -n "Have you upgraded Database (y/n)>"
    read choice
    echo
    case $choice in
      [yY] | [yY][Ee][Ss])
        break
        ;;
      [nN] | [n|N][O|o] )
        echo "Not done, you can't proceed the installation";
        exit 0
        ;;
      *)
        echo "That is not a valid choice, try again"
        ;;
    esac
  done

  #echo "Installing 7zip" | tee -a $LOGFILE
  #dpkg -i itop/p7zip-full_9.20.1~dfsg.1-4_amd64.deb  >> $LOGFILE 2>&1

  #echo "Copying openssl signing bin file for agent" | tee -a $LOGFILE
  #cp -rf itop/osslsigncode /usr/local/bin/
  #chmod +x /usr/local/bin/osslsigncode
 
  echo "Starting upgrade process..." | tee -a $LOGFILE

  updateRepo 
  #updateUFW "itop"
  updateLogrotate "itop"
  add_monit_service "itop"

  echo "Stopping itop service..." | tee -a $LOGFILE
  monit stop itop >> $LOGFILE 2>&1
  service itop stop >> $LOGFILE 2>&1
  sleep 10
  
  echo "Updating the itop application..." | tee -a $LOGFILE
  
  rm -fr /opt/itop/webapps/* /opt/itop/work/* /var/log/itop/* >> $LOGFILE 2>&1
  
  echo "Clearing the memcache..." | tee -a $LOGFILE
  nc membase 11211 <<EOF
flush_all
quit
EOF
  
  #echo "Updating tomcat server..." | tee -a $LOGFILE
  #update_tomcat
  keyFile="vistara.ks.p12"
  keyPass="N3t@dmin"
  if [ ! -f /opt/itop/conf/SSLCert.properties ]; then
	keyFile=`/bin/grep -E -o 'keystoreFile=\"(.*)\"' /opt/itop/conf/server.xml | sed 1q | sed 's/.*keystoreFile="\([^"]*\).*/\1/' | awk -F/  '{print $NF}'`
  	keyPass=`/bin/grep -E -o 'keystorePass=\"(.*)\"' /opt/itop/conf/server.xml | sed 1q | sed 's/.*keystorePass="\([^"]*\).*/\1/' | awk -F/  '{print $NF}'`
    echo "SSLCert.properties does not exist, so reading values from /opt/itop/conf/server.xml ..." | tee -a $LOGFILE
    echo "keystoreFile=\"${keyFile}\"" > /opt/itop/conf/SSLCert.properties
    echo "keystorePass=\"${keyPass}\"" >> /opt/itop/conf/SSLCert.properties
    chmod 777 /opt/itop/conf/SSLCert.properties    
  fi
  #echo "Reading SSL properties from file SSLCert.properties..." | tee -a $LOGFILE
  keyFile=`/bin/grep -E -o 'keystoreFile=\"(.*)\"' /opt/itop/conf/SSLCert.properties | sed 1q | sed 's/.*keystoreFile="\([^"]*\).*/\1/'`
  keyPass=`/bin/grep -E -o 'keystorePass=\"(.*)\"' /opt/itop/conf/SSLCert.properties | sed 1q | sed 's/.*keystorePass="\([^"]*\).*/\1/'`
  
  cp -fpr /opt/itop/conf/SSLCert.properties .
  cp -fpr /opt/itop/conf/$keyFile .
  
  echo "Updating the application war..." | tee -a $LOGFILE
  tar -xvzf itop/itop.tar.gz -C / >> $LOGFILE 2>&1
  chmod -R 755 /opt/itop  >> $LOGFILE 2>&1
  chown -R itop:itop /opt/itop  >> $LOGFILE 2>&1
  chmod -R 755 /etc/init.d/itop >> $LOGFILE 2>&1
  
  sed -e "s/address=\"@ITOP_IP@\"//g" -e "s/@SSL_FILE@/$keyFile/g" -e "s/@SSL_PASS@/$keyPass/g" /opt/itop/conf/server-eVistara-tpl.xml > /opt/itop/conf/server.xml | tee -a $LOGFILE
  chmod 755 /opt/itop/conf/server.xml
  chown itop.itop /opt/itop/conf/server.xml
  cp -fpr SSLCert.properties /opt/itop/conf/SSLCert.properties
  cp -fpr $keyFile /opt/itop/conf/$keyFile
  
  echo "Copying Linux NCare Agent packages..." | tee -a $LOGFILE
  tar -xvzf itop/linux-ncare-pkgs.tar.gz -C /opt/itop/ncare-agent/ >> $LOGFILE 2>&1
  chmod -R 755 /opt/itop/ncare-agent/  >> $LOGFILE 2>&1
  chown -R itop:itop /opt/itop/ncare-agent/  >> $LOGFILE 2>&1

  echo "Copying WebHelp files..." | tee -a $LOGFILE
  tar -xvzf itop/WebHelp.tar.gz -C /opt/itop/webapps/ >> $LOGFILE 2>&1
  chmod -R 755 /opt/itop/webapps/WebHelp  >> $LOGFILE 2>&1
  chown -R itop:itop /opt/itop/webapps/WebHelp  >> $LOGFILE 2>&1

  echo "Doing tcp tunnig and disabling ipv6..." | tee -a $LOGFILE
  tcp_tuning
  
  echo "Adding NFS monitoring script..." | tee -a $LOGFILE
  add_nfs_mon_script
  add_itop_cron_entries

  sed -i 's/activemq-server/kafka/g' /etc/hosts
  sed -i 's/msp-db/msp-db cassandra-db/g' /etc/hosts
  sed -i "5 a\127.0.0.1\tapp52" /etc/hosts

  echo "Restarting the services" | tee -a $LOGFILE
  monit start itop  >> $LOGFILE 2>&1
  sleep 5

  snmpd_change
  update_network_config

  echo "The node has been successfully updated...reboot the server now" | tee -a $LOGFILE
  return 0
}

stop_services(){
  if [ -f /etc/monit/conf.d/searchengine.monitrc ];
  then
    echo "Stopping service searchengine..."
    monit stop searchengine
    service searchengined stop
  fi
  
  if [ -f /etc/monit/conf.d/ncare.monitrc ];
  then
    echo "Stopping service ncare..."
    monit stop ncare
    service ncare stop
  fi
  
  if [ -f /etc/monit/conf.d/rdp2swf.monitrc ];
  then
    echo "Stopping service rdp2swf..."
    monit stop rdp2swf
    service rdp2swfd stop
  fi
  
  if [ -f /etc/monit/conf.d/itop.monitrc ];
  then
    echo "Stopping service itop..."
    monit stop itop
    service itop stop
  fi
}


valid_options(){
  while true; do
    echo ""
    echo "1. Just to stop required services before Database upgrade"
    echo "2. To upgrade the node"
    echo "0. Exit"
    echo
    
    echo -n "Enter your choice, or 0 for exit: "
    read choice
    echo
    case $choice in
      1)
        stop_services
        exit 0
        ;;
      2)
        break
        ;;
      0)
        echo "OK, see you later!"
        exit 0
        ;;
      *)
        echo "That is not a valid choice, try a number from 0 to 2."
        ;;
    esac  
  done
}


case "$1" in
  cn)
    if ! [ -f /etc/monit/conf.d/searchengine.monitrc -o -f /etc/monit/conf.d/rdp2swf.monitrc -o  -f /etc/monit/conf.d/ncare.monitrc ]
    then
      echo "It seems you run the script on this node with wrong server type.. so aborting.."
      exit 1
    fi
    valid_options
    update_ncare
    ;;
   
  db)
    valid_options
    update_db
    ;;
    
  itop)
    if ! [ -f /etc/monit/conf.d/itop.monitrc ]
    then
      echo "It seems you run the script on this node with wrong server type.. so aborting.."
      exit 1
    fi
    valid_options
    update_itop
    ;;
  *)
    echo "Usage: $0 {cn|db|itop}"
    exit 1
    ;;
esac

exit $?


